package Thread;

/**
 * 顺序（串行）和并发的对比
 */
public class Thread666 {
    public static void main(String[] args) throws InterruptedException {
        serial();
        concurrent();
    }

    private static final long count=10_0000_0000;

    //并发执行+10亿数据操作
    private static void concurrent() throws InterruptedException {
        Long start=System.nanoTime();
        Thread thread=new Thread(()->{
           //子线程进行+10亿操作
           long a=0;
            for (int i = 0; i <count ; i++) {
                a++;
            }
        });
        thread.start();
        //主线程执行+10亿操作
        long b=0;
        for (int i = 0; i < count; i++) {
            b++;
        }
        //等待子线程执行结束
        thread.join();
        long end=System.nanoTime();
        double alltime=(end-start)*1.0/1000/1000;
        System.out.println("并发执行共耗时"+alltime+"ms");
    }
    //串行进行20亿的累加
    private static void serial(){
        long start=System.nanoTime();
        long a=0;
        for (int i = 0; i < count; i++) {
            a++;
        }
        //下面的执行必须要等到上面的执行完毕才可以继续
        long b=0;
        for (int i = 0; i < count; i++) {
            b++;
        }
        long end=System.nanoTime();
        double alltime=(end-start)*1.0/1000/1000;
        System.out.println("顺序执行共耗时"+alltime+"ms");
    }
}
